var express = require('express');
var router = express.Router();
//引入数据库Query方法
const Query = require('../tools/Query')
//引入md5加密
const md5 = require('md5')
//引入jwt
const jwt = require('jsonwebtoken')
//引入uuid
const {v4:uuid} = require('uuid')
//引入token方法模块
let useToken = require('../tools/token')
//引入session
const cookieSession = require('cookie-session')
//引入svg-captcha验证码模块
const svgCaptcha = require('svg-captcha')
//引入serve-favicon 小图标
const favicon = require('serve-favicon')
const SECRET = 'lfhejkhferfesfbke'

//设置验证码

router.get('/captcha',(req,res)=>{
    //创建
    let captcha = svgCaptcha.create()
    //将验证码的值等于session
    cookieSession.captcha = captcha.text.toLowerCase()
    //设置类型
    res.type('svg')
    //返回
    res.send(cookieSession.captcha)
})

//注册页面初始化
router.get('/register', (req,res)=>{
    // res.send('register')
    let data={
        us:"1234"
    }
    let token=jwt.sign(data,SECRET)
    console.log(token)
    // 
    // let str="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cyI6IjEyMzQiLCJpYXQiOjE2MjkxMDcxMDN9.IolfwAoVGQryxcuN1Gf6pJ8uK2GocnkRqGt-dShBGQk"
     let str=req.headers.authorization
    let a=jwt.verify(str,SECRET)
    console.log(a)

})





// 注册逻辑代码
router.post('/api/register', async (req, res, next)=>{
    let SECRET = `endkfhek`

    //解构账号密码验证码
    let {username = 'user10',password = '123',repw = ''} = req.body
    password = md5(password)
    //创建注册事件
    let createDate = Date.now()
    //创建随机mid
    let uid = uuid()
    const user = {
        username:username,
        password:password
    }
    console.log(user);

    //加密信息
    let get = useToken.getToken(user)
    // 通过请求头解密
    let str = req.headers.authorization
    //解密  decrypt 
    let decrypt = useToken.verifyToken(str)
    //设置

    //创建token
    //将账号和密码添加到mySql中
    let adduserInfo = `INSERT INTO e_member (mid,username,password,createDate)VALUES('${uid}','${username}','${password}','${createDate}')`
    let register = `SELECT * FROM e_member`
    //查询数据库并解构返回值
    let [err,result] = await Query(register)
    //空对象接收数据
    let data = {}
    //判断是否错误
    if(!err){
        data = {
            msg:'ok',
            code:200,
            result
        }
    }else{
        data = {
            msg:err
        }
    }

    //解构data
    let userInfo = data.result 
    
    //判断内容是否为空
    if(username == '' || password == ''){
        res.send('输入内容不能为空')
        return
    }
         //判断账号是否注册过 注册过就停止代码运行
         let flag =  userInfo.some(item=>item.username == username)
         if(flag){
             res.send({
                 msg:'该用户已被注册',
                 status:500
             })
             return
         }else{
             res.send({
                 msg:'注册成功',
                 status:200
             })
             //声明对象写入注册的信息
           await Query(adduserInfo)
         }
    
});


router.post('/login',async(req,res)=>{
    //从前端获取来的账号密码
    let {username = 'admin1',password = '418abc503af93a4cc52c5c870f94fea6'} = req.body
    //mid
    let midStr = `SELECT mid FROM e_member WHERE username='${username}'`
    let [,mid] = await Query(midStr)
    //mid的值
    let midRes = String(mid[0].mid)
    //获取数据库的用户名和密码
    let userStr = `SELECT username,password FROM e_member`
    //接收
    let [,userInfo] = await Query(userStr)
    //every迭代判断账号和密码是否和数据库一样
   let flag = userInfo.some(item=>item.username == username && item.password == password)
//    res.send(flag)
    if(flag){
        //创建数据
        let data = {
            midRes,
            username,
            password
        }

        //创建token
        let token = useToken.getToken(data)
        res.send({
            msg:'登陆成功',
            midRes,
            status:200,
            result:token
        })
    }else{
        res.send({
            msg:'用户名或密码有误',
            status:500,
        })
    }
})



//个人信息
//  router.get('/api/profile', (req,res)=>{
//      //接收
//      const raw = String(req.headers.authorization).split(' ').pop()
//      console.log(raw);
//     // //jwt.verify验证
//     // const tokenData = jwt.verify(raw,SECRET)
//     // console.log(tokenData);
//     res.send('ok')
//  })

//登录


module.exports = router;
